package com.cooge.colletion.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Example;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

public abstract class BaseDao<T> {
	
	@Autowired
	@Qualifier("sessionFactory")
	private SessionFactory sessionFactory;

	public abstract Class<T> getEntityClass();
	public Session getSession() {
		return sessionFactory.getCurrentSession();
	}
	
	public Query createQuery(String queryString,String... params){
		Query query = this.getSession().createQuery(queryString);
		for(int i=0;i<=params.length;i++){
			query.setParameter(i, params[i]);
		}
		return query;
	}
	
	public T get(Integer id) {
		@SuppressWarnings("unchecked")
		T t = (T) this.getSession().get(getEntityClass(), id);
		return t;
	}

	@SuppressWarnings("unchecked")
	public List<T> getlist() {
		
		return this.getSession().createCriteria(getEntityClass()).list();

	}
	@SuppressWarnings("unchecked")
	public List<T> getList(T t){
			Criteria cri = this.getSession().createCriteria(this.getEntityClass());
			cri.add(Example.create(t));
			List<T> list =  cri.list();
			return list;
	}
	@SuppressWarnings("unchecked")
	public T save(T t){
		return (T) this.getSession().get(getEntityClass(),this.getSession().save(t));
	}
	
	@SuppressWarnings("unchecked")
	public List<T> getPageList(T t,int first,int max){
		Criteria cri = this.getSession().createCriteria(this.getEntityClass());
		cri.add(Example.create(t));
		cri.setFirstResult(first);
		cri.setMaxResults(max);
		List<T> list =  cri.list();
		return list;
	}
	
	@SuppressWarnings("unchecked")
	public List<T> getPageList(int first,int max){
		List<T> list=	this.getSession().createCriteria(getEntityClass()).setFirstResult(first).setMaxResults(max).list();
		return list;
	}

}
